﻿using System;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Media.Imaging;

using Coding4Fun.Controls;
using Coding4Fun.FakeCall.Data;
using Coding4Fun.Phone.Site.Controls;
using Expression.Blend.SampleData.PhoneType;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Coding4Fun.FakeCall
{
	public partial class SettingPivot : PhoneApplicationPage
	{
		private PhotoChooserTask photoLockScreenTask;
		private PhotoChooserTask photoPersonTask;
		private bool _photoPersonTaskShowing = false;
		private bool _photoLockScreenTaskShowing = false;
		public TimeSpan TimeSpan59Min { get { return TimeSpan.FromMinutes(59); } }
		public TimeSpan TimeSpan10Second { get { return TimeSpan.FromSeconds(10); } }

		private const string BaseMediaLocation = "Media/{0}";
		

		private FakeCallSettings _settings;
		public FakeCallSettings Settings
		{
			get { return _settings; }
			set
			{
				_settings = value;
				RaisePropertyChanged("Settings");
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		protected void RaisePropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion

		public SettingPivot()
		{
			InitializeComponent();
			
			TiltEffect.SetIsTiltEnabled(this, true);
			Settings = FakeCallSettings.Instance;

			DataContext = this;

			if (!Settings.ShowedMediaWarning)
			{
				MessageBox.Show("Fake Call will override any music playing.");
				Settings.ShowedMediaWarning = true;
				LoadRandomData();
				Settings.Save();
			}

			photoPersonTask = new PhotoChooserTask();
			photoLockScreenTask = new PhotoChooserTask();

			photoPersonTask.Completed += photoPerson_Completed;
			photoLockScreenTask.Completed += photoLockScreen_Completed;
		}

		private void LaunchAbout_Click(object sender, EventArgs e)
		{
			var prompt = new Coding4FunAboutPrompt();

			prompt.Show("Clint Rutkas", "ClintRutkas", "Clint@Rutkas.com", "http://betterthaneveryone.com");
		}

		private void LaunchApp_Click(object sender, EventArgs e)
		{
			if (!Settings.CustomizeSettings)
			{
				LoadRandomData();
			}
			else
			{
				// verify 
				Settings.PhoneType = (Item) personPhoneType.SelectedItem;
			}

			if (timeDelay.Value != null)
				Settings.TimeDelay = new TimeSpan(
					timeDelay.Value.Value.Hours,
					timeDelay.Value.Value.Minutes,
					timeDelay.Value.Value.Seconds);

			Settings.Save();
			Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/LockScreen.xaml", UriKind.Relative)));
		}

		private void LoadRandomData()
		{
			Settings.ExpandTalkOptions = false;
			Settings.VibratePhone = true;
			Settings.RingPhone = true;

			// lock screen
			Settings.LockScreenDate = DateTime.Now;
			Settings.LockScreenTime = DateTime.Now;

			var lockScreenUri = string.Format(BaseMediaLocation, "lockScreen_Seattle.jpg");
			SaveLockScreenPhoto(new WriteableBitmap(0, 0).FromResource(lockScreenUri));

			// apt
			Settings.AppointmentName = "Meet up with Friends";
			Settings.AppointmentStartTime = DateTime.Now;
			Settings.AppointmentEndTime = DateTime.Now.AddHours(1);

			// person
			var rnd = new Random();
			var isFormal = rnd.Next() % 2 == 0 ? true : false;
			var isFemale = rnd.Next() % 2 == 0 ? true : false;

			var personUri = isFormal ? string.Format(BaseMediaLocation, (isFemale) ? "daniela.jpg" : "matt.jpg") : string.Format(BaseMediaLocation, (isFemale) ? "Leslie.jpg" : "clint.jpg");
			SavePersonPhoto(new WriteableBitmap(0, 0).FromResource(personUri));
				
			Settings.PersonPhoneNumber = PhoneGenerator.GenerateNorthAmericanPhoneNumber();
			Settings.PersonName = isFemale ? PhoneGenerator.GenerateRandomGirl() : PhoneGenerator.GenerateRandomBoy();
			Settings.PhoneType = personPhoneType.SelectedItem as Item;
		}

		void photoLockScreen_Completed(object sender, PhotoResult e)
		{
			_photoLockScreenTaskShowing = false;

			if (e.TaskResult == TaskResult.OK)
			{
				SaveLockScreenPhoto(GetImageFromPhotoResult(e));
			}
		}

		void photoPerson_Completed(object sender, PhotoResult e)
		{
			_photoPersonTaskShowing = false;

			if (e.TaskResult == TaskResult.OK)
			{
				SavePersonPhoto(GetImageFromPhotoResult(e));
			}
		}

		void SaveLockScreenPhoto(WriteableBitmap bmp)
		{
			Settings.LockScreenPhoto = "LockScreenPhoto.jpg";
			lockScreenPhoto.Source = SavePhoto(Settings.LockScreenPhoto, bmp);
		}

		void SavePersonPhoto(WriteableBitmap bmp)
		{
			Settings.PersonPhoto = "PersonPhoto.jpg";
			PersonPhoto.Source = SavePhoto(Settings.PersonPhoto, bmp, 480, 450);
		}

		static WriteableBitmap GetImageFromPhotoResult(PhotoResult e)
		{
			e.ChosenPhoto.Position = 0;

			var bi = new BitmapImage();
			bi.SetSource(e.ChosenPhoto);
			return new WriteableBitmap(bi);
		}

		static WriteableBitmap SavePhoto(string fileName, WriteableBitmap bmp, int maxWidth = 480, int maxHeight = 800)
		{
			// Create virtual store and file stream
			using (var myStore = IsolatedStorageFile.GetUserStoreForApplication())
			{
				// Encode WriteableBitmap object to a JPEG stream.
				using (var myFileStream = myStore.OpenFile(fileName, FileMode.Create))
				{
					double ratioW = maxWidth*1.0/bmp.PixelWidth;
					double ratioH = maxHeight*1.0/bmp.PixelHeight;

					double ratio = ratioW * bmp.PixelHeight < maxHeight ? ratioH : ratioW;

					bmp.SaveJpeg(myFileStream, (int) (bmp.PixelWidth*ratio), (int) (bmp.PixelHeight*ratio), 0, 90);
				}
			}

			return bmp;
		}

		private void newLockScreenPhoto_Click(object sender, RoutedEventArgs e)
		{
			if (_photoLockScreenTaskShowing)
				return;

			_photoLockScreenTaskShowing = true;
			photoLockScreenTask.Show();
		}

		private void newPersonPhoto_Click(object sender, RoutedEventArgs e)
		{
			if (_photoPersonTaskShowing)
				return;

			_photoPersonTaskShowing = true;
			photoPersonTask.Show();
		}
	}
}